<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <div class="template-config-wrapper">
        <card :title="`自驾${_query.templateSort == 1 ? '短租' : '长租'}通用费用`">
          <!-- 系统模板 -->
          <page-form-row v-if="templateType == 1">
            <page-form-item style="margin-bottom: 0" field="templateName" label="通用费用名称" required>
              <i-input disabled v-model="form.templateName" :max-length="20" />
            </page-form-item>
            <page-form-item style="margin-bottom: 0" field="status" label="通用费用状态" required>
              <a-select disabled placeholder="请选择" v-model="form.status">
                <a-option v-for="item in dict.statusMap" :key="item.value" :label="item.label" :value="item.value" />
              </a-select>
            </page-form-item>
            <!-- 系统模板 应用门店 固定值为全部 -->
            <page-form-item style="margin-bottom: 0" label="应用门店" required>
              <a-input default-value="全部" disabled>
                <template #suffix>
                  <icon-down />
                </template>
              </a-input>
            </page-form-item>
          </page-form-row>
          <!-- 自定义模板 -->
          <template v-if="templateType == 2">
            <page-form-row>
              <page-form-item field="templateName" label="通用费用名称" required>
                <i-input v-model="form.templateName" :max-length="20" />
              </page-form-item>
              <page-form-item field="status" label="通用费用状态" required>
                <a-select placeholder="请选择" v-model="form.status">
                  <a-option v-for="item in dict.statusMap" :key="item.value" :label="item.label" :value="item.value" />
                </a-select>
              </page-form-item>
            </page-form-row>
            <page-form-row>
              <page-form-item style="margin-bottom: 0" field="siteIdList" label="应用门店" required size="2/3">
                <fast-transfer
                  style="width: 100%"
                  :titles="['未配置门店', '已选中门店']"
                  v-model="form.siteIdList"
                  :data-source="siteListAll"
                  :selected-list="selectedList"
                />
              </page-form-item>
            </page-form-row>
          </template>
        </card>
        <!-- 注意此处是循环对象 -->
        <card :title="item.feeName" v-for="(item, key) in form.tenantPriceFee" :key="key" :show-divider="key != 'depositFee'">
          <fee-section :option="item" :templateSort="_query.templateSort" :dict="dict" :feeType="key" />
        </card>
      </div>
    </page-form>
  </div>
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
</template>

<script setup name="CommonPriceForm" lang="ts">
  import { ref, onMounted, provide } from 'vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { getTemplateRelateSiteList, getTemplateDetail, getSysTemList, saveTemplate, editTemplate } from '@/api/business/common.js'
  import useNavigate from '@/hooks/useNavigate'
  import feeSection from './components/fee-section.vue'

  enum FeeType {
    baseFee = 0,
    addServiceFee = 1,
    preferentialFee = 2,
    otherFee = 3,
    extraFee = 4,
    refuseFee = 5,
    depositFee = 6,
    orderCancelFee = 7,
  }

  const { navigateBack } = useNavigate()
  const dict = usePageDict('tenantCostDict')
  const route = useRoute()
  const _query: any = route.query
  const _params = route.params
  const formRef = ref()
  const selectedList = ref()
  const form = ref<any>({
    status: 1, // 默认启用
    templateSort: _query.templateSort,
    // 费用集合
    tenantPriceFee: {
      baseFee: { feeType: 0, feeName: '基础费用', sysList: [], customList: [] },
      addServiceFee: { feeType: 1, feeName: '增值服务费', sysList: [], customList: [] },
      preferentialFee: { feeType: 2, feeName: '优惠费用', sysList: [], customList: [] },
      otherFee: { feeType: 3, feeName: '其他费用', sysList: [], customList: [] },
      extraFee: { feeType: 4, feeName: '额外费用', sysList: [], customList: [] },
      refuseFee: { feeType: 5, feeName: '额外费用退款', disabled: true, sysList: [], customList: [] },
      orderCancelFee: { feeType: 7, feeName: '订单取消费', sysList: [], customList: [] },
      depositFee: { feeType: 6, feeName: '押金费用', sysList: [] },
    },
  })
  provide('dict', dict)
  // 获取门店未关联列表
  const getAllSiteLIst = async (param = {}) => {
    const res = await getTemplateRelateSiteList(param)
    return res.result
  }
  const rules = ref({
    templateName: { required: true, message: '请输入通用费用名称', trigger: 'change' },
    siteIdList: { required: true, message: '请选择应用门店', trigger: 'change' },
  })

  // 模板类型 自定义类型
  const templateType = ref(2)
  // 编辑
  let templateId = _params.id

  // 全部门店
  const siteListAll = ref([])
  onMounted(async () => {
    if (templateId) {
      // 模板类型
      templateType.value = _query.templateType
      // 获取模板详情
      getTemplateDetail({ id: templateId }).then(async (res: any) => {
        const result = res.result
        // 获取已关联门店列表
        const tenantPriceSiteList = result.tenantPriceSiteList || []

        // 处理 form 数据 开始
        form.value.id = templateId
        form.value.status = result.status
        form.value.templateName = result.templateName
        // 自定义模板 siteIdList 传 null
        form.value.siteIdList = templateType.value == 2 ? tenantPriceSiteList.map((item: any) => item.siteId) : null
        // 处理 form 数据 结束

        // 自定义模板
        if (templateType.value == 2) {
          // 获取门店列表
          let allList = await getAllSiteLIst({ id: templateId, templateSort: _query.templateSort })
          // 全部门店
          if (allList.length > 0) {
            siteListAll.value = allList.map((item: any) => {
              return {
                label: item.siteName,
                value: item.siteId || item.id,
              }
            })
          }
        }
        selectedList.value = []

        const tenantPriceFeeList = result.tenantPriceFeeList
        initFeeList(tenantPriceFeeList)
      })
    } else {
      // 获取门店列表
      let siteList = await getAllSiteLIst({ templateSort: _query.templateSort })
      if (siteList.length > 0) {
        siteListAll.value = siteList.map((item: any) => {
          return {
            label: item.siteName,
            value: item.id,
          }
        })
      }
      getSysTemList().then((res: any) => {
        const result = res.result
        initFeeList(result)
      })
    }
  })

  // 处理费项
  const initFeeList = (list: any[]) => {
    let tenantPriceFee = form.value.tenantPriceFee

    list.forEach((item: any) => {
      let option = {
        id: item.id,
        feeId: item.feeId,
        feeName: item.feeName,
        feeType: item.feeType,
        feeUnit: item.feeUnit,
        feeAmount: item.feeAmount,
        payType: item.payType,
        payTypeStr: item.payTypeStr,
      }

      if (item.isSystem) {
        tenantPriceFee[FeeType[item.feeType]].sysList?.push(option)
      } else {
        tenantPriceFee[FeeType[item.feeType]].customList?.push(option)
      }
    })
  }
  const buildParam = () => {
    const param = {
      ...form.value,
    }
    let tenantPriceFee = param.tenantPriceFee
    let tenantPriceFeeList = []
    for (let k in tenantPriceFee) {
      let item = tenantPriceFee[k]
      if (item.sysList) {
        tenantPriceFeeList.push(...item.sysList)
      }

      if (item.customList) {
        tenantPriceFeeList.push(...item.customList)
      }
    }
    param.tenantPriceFeeList = tenantPriceFeeList
    delete param.tenantPriceFee

    return param
  }
  // 模板保存
  const okLoading = ref(false)
  const submitFn = (noticeSuccess: any) => {
    console.log('param', buildParam())
    formRef.value.validate((error: any) => {
      console.log(error, 'error')
      if (!error) {
        const param = buildParam()
        // 编辑
        let api = saveTemplate
        if (templateId) {
          api = editTemplate
        }
        okLoading.value = true
        api(param)
          .then(() => {
            noticeSuccess()
            navigateBack()
          })
          .finally(() => {
            okLoading.value = false
          })
      }
    })
  }
</script>

<style lang="less" scoped></style>
